`
https://leetcode.cn/problems/daily-temperatures/
`

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function (temperatures) {
  const n = temperatures.length
  const res = new Array(n).fill(0)
  const stack = []

  // 保持栈是递减的
  // 如果遇到非递减的情况，将要新加入的元素下标与栈顶元素下标的差值即为栈顶元素位置的答案
  for (let i = 0; i < n; i++) {
    const num = temperatures[i]
    while (stack.length && temperatures[stack[stack.length - 1]] < num) {
      const idx = stack.pop()
      res[idx] = i - idx
    }
    stack.push(i)
  }

  return res
};